const Service = require('egg').Service;
// const mock  = require('mockjs')
// const {list} = mock.mock({
//   "list|300": [
//     {
//       'title':"@ctitle(10,20)",
//       'price|1-1000':1,
//       'image': "https://unsplash.it/400/800/?@name"
//     }
//   ]
// })
// list.forEach(item => {
//   this.app.mysql.insert('shops', item)
// })
class HomeService extends Service {
  async getList() {
    const {ctx,app} = this;
    // 分页 模糊查询 
    const {pageIndex,pageSize,keyword} = ctx.query;
    let sql = `select * from shops where 1=1 `
    let sqlCount = `select count(id) as total from shops where 1=1 `
    if(keyword) {
      sql += `and title like "%${keyword}%" `
      sqlCount += `and title like "%${keyword}%" `
    }
    if(pageIndex && pageSize) {
      sql += `limit ${(pageIndex-1)*pageSize},${pageSize}`
    }
    const data = await app.mysql.query(sql)
    const [{total}] = await app.mysql.query(sqlCount)
    return {data,total}
  }
  async getDetail() {
    const {ctx,app} = this;
    // 获取详情
    const {id} = ctx.params;
    const data = await app.mysql.get('shops', {id})
    return data
  }
  async like() {
    const {ctx,app} = this;
    // 获取详情
    const {user_id,shop_id} = ctx.request.body;
    // 判断有没有
    const isHave = await app.mysql.get('likes', {user_id,shop_id})
    let data;
    if(isHave) {
      data = await app.mysql.delete('likes', {user_id,shop_id})
    } else {
      data = await app.mysql.insert('likes', {user_id,shop_id})
    }
    return data
  }
}

module.exports = HomeService;